//
//  NEDRouter+Jump.m
//  NEDRouter
//
//  Created by 98du on 2021/12/1.
//

#import "NEDRouter+Jump.h"
#import <SafariServices/SafariServices.h>
#import "UIViewController+NEDRouterParame.h"

@implementation NEDRouter (Jump)


+ (UIViewController *)jump_openWebVSafariByURL:(NSString *)urlStr{
    /** 去除空格 */
    urlStr = [urlStr stringByReplacingOccurrencesOfString:@" " withString:@""];
    if(!urlStr || [urlStr isEqualToString:@""]){
        NSLog(@"%s 跳转为空",__func__);
        return nil;
    }
    urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSMutableCharacterSet URLFragmentAllowedCharacterSet]];
    NSURL * URL = [NSURL URLWithString:urlStr];
    if(!URL.scheme){
        NSLog(@"%s 跳转为空 %@",__func__,urlStr);
        return nil;
    }
    if ([URL.scheme isEqualToString:[NEDRouter sharedManager].urlScheme]) {
        return [NEDRouter ned_openLink:urlStr];
    }
    SFSafariViewController *safariVc = [[SFSafariViewController alloc] initWithURL:URL];
    if (@available(iOS 11.0, *)) {
        safariVc.dismissButtonStyle = SFSafariViewControllerDismissButtonStyleClose;
    } else {
        // Fallback on earlier versions
    }
    [NEDCurrentViewController() presentViewController:safariVc animated:YES completion:nil]; // 推荐使用modal自动处理 而不是push
    return safariVc;
}

/// 打开内部网页
+ (UIViewController *)jump_openWebViewByURL:(NSString *)urlStr params:(NSDictionary * _Nullable)params{
    if([NEDRouter sharedManager].openWebViewController){
        return [NEDRouter sharedManager].openWebViewController(urlStr,params);
    }else{
        if([NEDRouter sharedManager].errorHandler){
            [NEDRouter sharedManager].errorHandler(NEDRouterErrorCodeWebviewCallbackUnrealized, @"网页打开方式block openWebViewController 未实现", @{@"url":urlStr,@"params":params?:@{}});
        }
        return nil;
    }
}

/** 打开链接 */
+ (void)jump_openURLOutside:(NSString *)urlString {
    NSURL *url = [NSURL URLWithString:urlString];
    [self __applicationOpenURL:url];
}

+(void)jump_callPhone:(NSString *)phoneNum{
    NSString * str = [NSString stringWithFormat:@"telprompt://%@",phoneNum];
    if (@available(iOS 10.0, *)) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str] options:@{} completionHandler:nil];
    } else {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
    }
}

/// 打开系统设置
+ (void)jump_openSystemSetting{
    NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    [self __applicationOpenURL:url];
}


#pragma mark - privite

+ (void)__applicationOpenURL:(NSURL *)url{
    if ([[UIApplication sharedApplication] canOpenURL:url]) {
        if (@available(iOS 10.0, *)) {
            [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
                
            }];
        } else {
            [[UIApplication sharedApplication] openURL:url];
        }
    }
}

@end
